package com.example.maryttsspringbootdemo.controller;

import com.example.maryttsspringbootdemo.recorder.AudioRecorder;
import com.example.maryttsspringbootdemo.service.MaryTtsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

@Component
@Slf4j
public class AudioWebSocket extends TextWebSocketHandler {

    @Autowired
    private MaryTtsService ttsService;
    @Autowired
    private AudioRecorder audioRecorder;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        log.info("客户端 {} 连接建立", session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        log.info("客户端 {} 连接关闭", session.getId());
    }


    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        String text = message.getPayload();

        try {
//            byte[] audioBytes = ttsService.textToSpeech(text);
            // 按照标点符号分割句子，循环发送
            String[] sentences = text.split("[.?!:]");
            for (String sentence : sentences) {
                log.info(sentence);
//                String fileName = "audio_" + UUID.randomUUID() + ".wav";
                String fileName = "audio_" + session.getId() + ".wav";
                byte[] sentenceBytes = ttsService.textToSpeech(sentence + ".");
                audioRecorder.writeToWav(sentenceBytes, fileName);
                log.info("音频文件已保存: {}", fileName);
                // 读取wav文件为byte []
                byte[] wavBytes = Files.readAllBytes(Paths.get(fileName));
                
                // 发送 Base64 编码的音频数据
                String base64Audio = java.util.Base64.getEncoder().encodeToString(wavBytes);
                session.sendMessage(new TextMessage("{\"audio\":\"" + base64Audio + "\"}"));
            }
   
            
        } catch (Exception e) {
            log.error("语音转换或保存失败", e);
            session.sendMessage(new TextMessage("{\"error\": \"" + e.getMessage() + "\"}"));
        }
    }
}